﻿using Microsoft.EntityFrameworkCore;

using PLCS.App.Shared.Extensions;
using PLCS.App.Shared.Models;
using PLCS.Application.Contracts.LogShowApp.Dtos;
using PLCS.Client.IService;
using PLCS.Client.IService.LogManager;
using PLCS.Client.Service.LogManager;
using PLCS.Shared.Common.Constant;

using System.Collections.ObjectModel;

using Volo.Abp.Application.Dtos;

namespace PLCS.App.Shared.ViewModels;

public class NavigationCurdViewModel<Dto, EditDto, IService> : NavigationViewModel
    where IService : IBaseService<Dto, EditDto>
    where Dto : EntityDto<Guid>
    where EditDto : EntityDto<Guid>
{
    private ObservableCollection<Dto> _dataGridList;

    public ObservableCollection<Dto> DataGridList
    {
        get { return _dataGridList; }
        set { SetProperty(ref _dataGridList, value); }
    }

    public IEnumerable<Dto> Models { get; set; }

    public NavigationCurdViewModel(IService service)
    {
        AddCommand = new DelegateCommand(Add);
        EditCommand = new DelegateCommand<object>(Edit);
        QueryCommand = new DelegateCommand(async () => await RefreshAsync());
        DeleteCommand = new DelegateCommand<object>(Delete);
        _service = service;
        this._logShowService = new OperationLogService();
    }

    #region 搜索条件

    private string _search;

    public string Search
    {
        get { return _search; }
        set { SetProperty(ref _search, value); }
    }

    #endregion 搜索条件

    #region 翻页

    /// <summary>
    /// 总数
    /// </summary>
    private int _totalCount = 0;

    public int TotalCount
    {
        get { return _totalCount; }
        set { _totalCount = value; RaisePropertyChanged(); }
    }

    /// <summary>
    /// 当前页大小
    /// </summary>
    private int _pageSize = GlobalVariable.PageSize;

    public int PageSize
    {
        get { return _pageSize; }
        set { _pageSize = value; RaisePropertyChanged(); }
    }

    /// <summary>
    /// 当前页
    /// </summary>
    private int _pageIndex = 1;

    public int PageIndex
    {
        get { return _pageIndex; }
        set { _pageIndex = value; RaisePropertyChanged(); }
    }

    /// <summary>
    /// 分页总数
    /// </summary>
    private int _pageCount;

    public int PageCount
    {
        get { return _pageCount; }
        set { _pageCount = value; RaisePropertyChanged(); }
    }

    public readonly IService _service;
    private readonly IOperationLogService _logShowService;

    /// <summary>
    /// 首页
    /// </summary>
    public virtual void GoHomePage()
    {
        if (PageIndex == 1) return;

        PageIndex = 1;

        GetPageData(PageIndex);
    }

    /// <summary>
    /// 上一页
    /// </summary>
    public virtual void GoOnPage()
    {
        if (PageIndex == 1) return;

        PageIndex--;

        GetPageData(PageIndex);
    }

    /// <summary>
    /// 下一页
    /// </summary>
    public virtual void GoNextPage()
    {
        if (PageIndex == PageCount) return;

        PageIndex++;

        GetPageData(PageIndex);
    }

    /// <summary>
    /// 尾页
    /// </summary>
    public virtual void GoEndPage()
    {
        PageIndex = PageCount;

        GetPageData(PageCount);
    }

    /// <summary>
    /// 获取数据
    /// </summary>
    /// <param name="pageIndex"></param>
    public virtual void GetPageData(int pageIndex)
    {
        Models = Models.SearchQuery(Search);
        TotalCount = Models.Count();
        SetPageCount();
        DataGridList = Models.Skip((pageIndex - 1) * PageSize).Take(PageSize).ToObservable();
    }

    /// <summary>
    /// 设置页数
    /// </summary>
    public virtual void SetPageCount()
    {
        PageCount = (int)Math.Ceiling(TotalCount / (double)PageSize);
    }

    public DelegateCommand GoHomePageCommand => new DelegateCommand(GoHomePage);

    public DelegateCommand GoOnPageCommand => new DelegateCommand(GoOnPage);

    public DelegateCommand GoNextPageCommand => new DelegateCommand(GoNextPage);

    public DelegateCommand GoEndPageCommand => new DelegateCommand(GoEndPage);

    #endregion 翻页

    #region 增删改查

    public DelegateCommand AddCommand { get; private set; }
    public DelegateCommand<object> EditCommand { get; private set; }
    public DelegateCommand QueryCommand { get; private set; }
    public DelegateCommand<object> DeleteCommand { get; private set; }

    /// <summary>
    /// 新增
    /// </summary>
    public async void Add()
    {
        var dialogResult = await dialog.ShowDialogAsync(GetPageName("Detail"));
        if (dialogResult.Result == ButtonResult.OK)
            await RefreshAsync();
    }

    /// <summary>
    /// 编辑
    /// </summary>
    public async void Edit(object model)
    {
        DialogParameters param = new DialogParameters
        {
            { "Value", model }
        };
        var dialogResult = await dialog.ShowDialogAsync(GetPageName("Detail"), param);
        if (dialogResult.Result == ButtonResult.OK)
            await RefreshAsync();
    }

    #region 优化前

    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="model"></param>
    //public virtual async void Delete(object model)
    //{
    //    var res = ShowQuestion("确认删除吗？");
    //    if (!res)
    //        return;
    //    if (model != null)
    //    {
    //        var data = model as Dto;
    //        await _service.DeleteByIdAsync(data.Id);
    //        await RefreshAsync();
    //    }
    //    ShowMessage("操作成功");
    //}

    #endregion 优化前

    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="model"></param>
    public virtual async void Delete(object model)
    {
        var res = ShowQuestion("确认删除吗？");
        if (!res)
            return;
        if (model != null)
        {
            var data = model as Dto;
            await _service.DeleteByIdAsync(data.Id);
            DataGridList.Remove(data);
            TotalCount--;
            ShowMessage("操作成功");
        }
    }

    public override async Task RefreshAsync()
    {
        try
        {
            UpdateLoading(true);
            Models = await _service.GetListAsync();
            GetPageData(PageIndex = 1);
        }
        finally { UpdateLoading(false); }
    }

    #endregion 增删改查

    /// <summary>
    /// 获取弹出页名称
    /// </summary>
    /// <param name="methodName"></param>
    /// <returns></returns>
    private string GetPageName(string methodName) => GetType().Name.Replace("ViewModel", methodName + "View");

    public override async Task OnNavigatedToAsync(NavigationContext navigationContext)
    {
        if (DataGridList == null || DataGridList.Count == 0)
            await base.OnNavigatedToAsync(navigationContext);
    }
}